<template>
	<view class="content">
		<!-- tabbar -->
		<view class="tabbar">
			<u-navbar :is-back="false" :is-fixed="false" :border-bottom="false" title="币币交易">
				<!-- <view class="navbar-user" slot="right">
          <u-icon name="search" size="40" color="#4f5355"></u-icon>
        </view> -->
			</u-navbar>
		</view>
		<!-- container -->
		<view class="container">
			<view class="vintops">
				<view class="v-name">
						<view @tap="showCoinList = true">	<text class="text" >{{ seltCoinbase.label }}</text>
			 <u-icon style="margin-right: 10upx;"  name="arrow-down" color="#00a2e9" size="24" label="选择币种"></u-icon>   </view>
          <u-select v-model="showCoinList" :list="aCoinList" @confirm="onSeltConfirm"></u-select>
				</view>
				<view class="v-right">
					<text class="t1">{{ (priceRate.rate).toFixed(2)  }}%</text>
					<text class="t2">{{ priceRate.price }}</text>
					<image src="../../static/icon/icon-us.png" mode="aspectFit" class="t-icon"></image>
				</view>
			</view>
			<view class="wrap">
				<u-row gutter="30" align="top">
					<u-col span="7">
						<view class="selt-swint">
							<text class="text" :class="[type == 1 ? 't-bg1' : '']" @tap="onSeltType(1)">买入</text>
							<text class="text" :class="[type == 2 ? 't-bg1' : '']" @tap="onSeltType(2)">卖出</text>
							<image :src="`/static/bv${type}.png`" mode="aspectFit" class="bvin"></image>
						</view>
						<view class="type-info">
							<view class="type-drop">
								<text>限价{{btnText}}</text>
								<!-- <u-icon name="arrow-down" size="20" color="#c0c0c0" class="icon"></u-icon> -->
							</view>
							<view class="type-icon"><u-icon name="question-circle" size="42" color="#ccc"></u-icon></view>
						</view>
						<view class="calc-nums">
							<u-number-box v-model="iPrice" :step="0.01" :disabled="unit == 'WZ'" @change="valChange"></u-number-box>
							<text class="text">单位：CNY</text>
						</view>
						<view class="calc-nums">
							<u-number-box v-model="nums2" :step="1"  :max="buyAmount" :placeholder="`数量(${unit})`" @change="valChange"></u-number-box>
							<view class="calc-btns">
								<u-button size="mini" type="primary" ripple :custom-style="customStyle" @click="seltAmount(0.25)">25%</u-button>
								<u-button size="mini" type="primary" ripple :custom-style="customStyle" @click="seltAmount(0.5)">50%</u-button>
								<u-button size="mini" type="primary" ripple :custom-style="customStyle" @click="seltAmount(0.75)">75%</u-button>
								<u-button size="mini" type="primary" ripple :custom-style="customStyle" @click="seltAmount(1)">100%</u-button>
							</view>
						</view>
						<view class="have-amount">
							<view class="textams" v-if="type==1">
								<text>可用</text>
								<text class="amount-show">{{ Number(amount).toFixed(2) }} USDT</text>
							</view>
							<view class="textams">
								<text>可{{typeText}}</text>
								<text class="amount-show">{{ Number(buyAmount) }} {{ unit }}</text>
							</view>
							<view class="amount-trans"><image src="../../static/icon/icon_dropdown_large.webp" mode="aspectFit" class="icon"></image></view>
						</view>
						<view class="on-buystart">
							<u-button
								:disabled="!isDisabled  || nosubmit"
								:custom-style="{
									height: '64rpx'
								}"
								:type="getSubType"
								 @click="trading"
							>
								{{btnText}} {{ unit }}
							</u-button>
						</view>
					</u-col>
					<u-col span="5">
						<view class="seinfo-card">
							<view class="type-drop">
								<text>委托列表</text>
					<!-- 			<u-icon name="arrow-down" size="20" color="#c0c0c0" class="icon"></u-icon> -->
							</view>
							<u-gap height="2" bg-color="#eee" margin-top="8" margin-bottom="20"></u-gap>
							<view class="ucard-tables">
								<u-table border-color="#131e30" bg-color="#131e30" font-size="24" padding="0" align="left">
									<u-tr>
										<u-th>价格(CNY)</u-th>
										<u-th align="right">数量({{ unit }})</u-th>
									</u-tr>
									<u-tr v-for="(item, index) in  salelist " :key="index" @click="onTrinfo(item.uiPrice)">
										<u-td color="#db5f6a">{{ item.uiPrice }}</u-td>
										<u-td align="right">{{ item.num }}</u-td>
									</u-tr>
								</u-table>
								<u-gap height="2" bg-color="#071724" margin-top="8" margin-bottom="8"></u-gap>
								<u-table border-color="#131e30" bg-color="#131e30" font-size="24" padding="0" align="left">
									<u-tr v-for="(item, index) in buylist" :key="index" @click="onTrinfo(item.uiPrice)">
										<u-td color="#4fb86e">{{ item.uiPrice }}</u-td>
										<u-td align="right">{{ item.num }}</u-td>
									</u-tr>
								</u-table>
							</view>
						</view>
					</u-col>
				</u-row>
			</view>
		</view>
		<u-gap height="20" bg-color="#071724" margin-top="8" margin-bottom="8"></u-gap>
		<view class="sein-list">
			<view class="sein-title"><u-section :bold="false" title="限价委托" sub-title="查看成交单" :show-line="false" @click="showTrading"> </u-section></view>
			<view class="sein-content">
				<scroll-view scroll-y="true" style="height: 100%;">
					<view class="" v-if="userinfo.applylist.length >0">
						<view class="itembox" v-for="(item, index) in userinfo.applylist" :key="index">
							<text class="tdtxt1">{{item.uiPrice}}</text>
							<text class="tdtxt2">{{item.uiSQShenyuJiner}}</text>
							<text class="tdtxt3">{{item.uiDate}}</text>
							<view class="tdain" @click="cancelOrder(item.uiId)"><text>取消委托</text></view>
						</view>
					</view>
					<view class="sein-nomore" v-else><text>本币对暂无委托</text></view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
import { CUser } from '@/common/cache/user.js';
var cache_user = new CUser();
export default {
	data() {
		return {
			list: ['', '', '', '', ''],
			type: 1,
			price: 0,
			nums2: '',
			amount: 0,
			customStyle: {
				'background-color': '#192943',
				'font-size': '22rpx',
				width: '86rpx',
				height: '48rpx',
				color: '#999'
			},
			userinfo: {applylist:[]},
			buylist :[],
			salelist :[],
			btnText :'买入',
			typeText :'买',
			nosubmit : false,
      showCoinList: false,
      seltCoinbase: {},
      aCoinList: [],
      unit: 'DT',
      rateList: null,
	  intervalID : 0,
	  coinId:0,
      iPrice: 0
	 
		};
	},
  onLoad(options) {
    //console.log('options',options)
  if (options.type == 1) {
      this.onSeltType(2)
   }
	//个人数据
	uni.showLoading({
	  mask: true
	})
	

		
	this.coinId = options.coin || ''
	
	this.getListCoin().then(() => {

	  this.getBuyData();
	  uni.hideLoading()
	  this.getTradubgData();
	  
	  		
	  this.price = this.priceRate.price

	})
	

	//this.buyAmount();


  },
	computed: {
    priceRate () {
      let _r = {
        rate: 0,
        price: 0,
      }
      if (this.rateList) {
        let m = this.rateList.get(this.unit)
        _r = {
          rate: ((m.coinAPrice - m.coinAOldPrice) / m.coinAOldPrice) * 100,
          price: (m.coinAPrice-0).toFixed(2)
        }
      }
      this.iPrice = _r.price
      return _r
    },
		isDisabled() {
			return Boolean(this.price) && Boolean(this.nums2);
		},
		buyAmount() {
			if(this.type ==1) //可买
				return parseInt(this.amount / this.price) *7;
				else{ //可卖
          let money = this.userinfo.uBenjin
          switch (this.unit) {
            case 'WZ':
            money = this.userinfo.uBenjin
            break;
            case 'DTSM':
            money = this.userinfo.uDTSM
            break;
          }
					return parseInt(money);
				}
		},
		getSubType(){
			if(this.type ==1) //可买
				return 'success'
				else
				return 'error'
		}
	},

	onShow() {

	
	 this.intervalID =  setInterval(this.getTradubgData, 5000);
	},
	
	onHide(){
		clearInterval(this.intervalID);
	},
	
	
	

	methods: {
    onTrinfo (price) {
      let amount = Number(price)
      if (!isNaN(amount)) {
        if (this.unit !== 'DT') {
          this.iPrice = amount
        }
      }
    },
    getListCoin () {
      return new Promise((resolve) => {
        this.$api.http.get('assistance/tradinghall/getCoinList')
        .then(res => {
          this.aCoinList = []
          if (res.length) {
            this.rateList = new Map()
            res.map((item) => {
              this.aCoinList.push({
                label: item.coinA + '/' + item.coinB,
                value: item.id,
				price :item.coinAPrice
              })
              this.rateList.set(item.coinA, item)
            })
            this.seltCoinbase = this.aCoinList[0] || {}
            if (this.seltCoinbase.label) {
              this.unit = this.seltCoinbase.label.split('/')[0]
            }
			
			
            
            if (this.coinId) {
              for (let i = 0; i < this.aCoinList.length; i ++) {
                if (this.aCoinList[i].value == this.coinId) {
                  this.seltCoinbase = this.aCoinList[i]
				   this.unit = this.seltCoinbase.label.split('/')[0]
                  break;
                }
              }
            }
          }
          resolve(res)
        });
      })
    },
    onSeltConfirm (e) {
      this.seltCoinbase =e[0];
      this.nums2 = ''

      if (this.seltCoinbase.label) {
        this.unit = this.seltCoinbase.label.split('/')[0]
      }
	  
	  
	    this.price = this.priceRate.price

      this.getBuyData();
     this.getTradubgData();
    },
		seltAmount(rat) {
			if(this.type==1) //买入
			this.nums2 = parseInt(this.buyAmount * rat);
			else{ //卖出
				this.nums2 = parseInt(this.buyAmount*  rat);
			}
		},
		valChange(e) {
			console.log(e);
		},
		onSeltType(index) {
			this.type = index;
			//买入
			if(this.type ==1){
				this.btnText = '买入';
				this.typeText = '买';
					this.getBuyData();
			}else{ //卖出
				this.btnText = '卖出';
					this.typeText = '卖';
						this.getSaleData();
			}
			this.nums2 = '';
		
			
		},

		getBuyData() {
			var self = this;
			this.$api.http.get('assistance/index/extensionBuyGetData', {
        coinType: this.seltCoinbase.value
      }).then(res => {
	
				if(res.status ==200){
						self.userinfo = res.data;
							
					self.amount = res.data.uMoney;
				
					}
			});
		},
		getSaleData() {
				var self = this;
			this.$api.http.get('assistance/index/extensionSaleGetData', {
        coinType: this.seltCoinbase.value
      }).then(res => {
				if(res.status ==200){
					self.userinfo = res.data;
					self.amount = res.data.uMoney;
				}
				
			});
		},

		getUserInvestTotal() {
			var self = this;
			this.$api.http.get('assistance/index/getUserInvestTotal', {
        coinType: this.seltCoinbase.value
      }).then(res => {
				if(res.status ==200){
				if(res.data.buylist){
					
					self.buylist = res.data.buylist; //赋值给买列表
					var bl = (res.data.buylist).length;
					for(var i = 5; i > bl; i--){
						self.buylist.push({'uiPrice':'--', 'num':'--'})
					}		
				};
				
				if(res.data.salelist){
					
					self.salelist = res.data.salelist;; //赋值给卖列表
					var sl = (res.data.salelist).length;
					
					for(var i = 5; i > sl; i--){
						self.salelist.unshift({'uiPrice':'--', 'num':'--'})
					}		
					
				};
					
				}
				
				
			});
		},
		trading(){
			
			var action = "";
			if(this.type ==1)//买入
				action ="creaWantInvest";
			else
				action ="wantUnInvestAction";
			
			var self = this;
			uni.showModal({
				title: '提示',
				content: '确认要'+this.btnText+'？',
				success: function(res) {
					if (res.confirm) {
			
			self.nosubmit = true;//禁用按钮
			
			self.$api.http.post('/assistance/tradinghall/'+action, {
        coinType: self.seltCoinbase.value,
        'uiUJiner':self.nums2,
        price: self.price
      }).then(res => {
				self.$api.msg(res.msg)
				
				self.nosubmit = false;
				if(res.status ==200){
					
					if(self.type ==1)//买入
						self.getBuyData();
					else
						self.getSaleData();
						
				
				}
			
			})
			
			}}})
			
			
		},
		
		cancelOrder(id){
			var self = this;
			uni.showModal({
				title: '提示',
				content: '确认要取消委托吗？',
				success: function(res) {
					if (res.confirm) {
			
			self.nosubmit = true;//禁用按钮
			
			self.$api.http.post('/assistance/tradinghall/cancelOrder', {
        'id':id,
        coinType: self.seltCoinbase.value
      }).then(res => {
				self.$api.msg(res.msg)
				
				self.nosubmit = false;
				if(res.status ==200){
				
				if(self.type ==1)//买入
					self.getBuyData();
				else
					self.getSaleData();
					
			
				}
			
			})
			
			}}})
		},
		
		
		getTradubgData(){
			
			this.getUserInvestTotal();
			var self = this;
			this.$api.http.get('assistance/tradinghall/getCoinByID',{coinType: this.seltCoinbase.value})
			.then(res => {
				//self.price = res.coinAPrice
				self.rateList.set(res.coinA, res)
				
				});
			
		},
		
		showTrading(){
			var coinType =this.seltCoinbase.value;
			uni.navigateTo({
				url: './orderList?coinType='+coinType
			});
		}
		
		
		
	}
};
</script>

<style lang="scss">
.container {
	padding: 0 30rpx 20rpx;
}
.navbar-user {
	padding: 0 30rpx;
}
.vintops {
	padding: 20rpx 0;
	border-bottom: 1rpx solid $uni-text-color-grey;
	display: flex;
	align-items: center;
	justify-content: space-between;
	.v-name {
		font-size: $uni-font-size-sm;
		color: $text-color;
		.text {
			margin-right: 10rpx;
		}
	}
	.v-right {
		display: flex;
		align-items: center;
		.t1 {
			font-size: $uni-font-size-lg;
			color: #db5f6a;
		}
		.t2 {
			color: $color-theme;
			font-size: $uni-font-size-base;
			margin: 0 16rpx;
		}
		.t-icon {
			width: 42rpx;
			height: 42rpx;
		}
	}
}
.wrap {
	margin-top: 20rpx;
}
.selt-swint {
	display: flex;
	align-items: center;
	position: relative;
	height: 62rpx;
	.text {
		background-color: #f2f2f2;
		width: 50%;
		text-align: center;
		height: 62rpx;
		line-height: 62rpx;
		border-radius: $uni-border-radius-base;
	}
	.t-bg1 {
		background-color: #4eb772;
		color: #fff;
	}
	.bvin {
		position: absolute;
		left: 50%;
		top: 0;
		width: 60rpx;
		height: 100%;
		margin-left: -30rpx;
		z-index: 3;
	}
}
.type-info {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12rpx 0;
}
.type-drop {
	font-size: $uni-font-size-base;
	color: $text-color;
	display: flex;
	align-items: flex-start;
	.icon {
		margin-left: 10rpx;
		margin-top: 6rpx;
	}
}
.calc-nums {
	display: flex;
	flex-direction: column;
	.text {
		color: #8e8e8e;
		margin: 12rpx 0;
	}
}
.calc-btns {
	display: flex;
	justify-content: space-between;
	padding: 12rpx 0;
}
.textams {
	font-size: $uni-font-size-sm;
	color: $color-theme;
	padding: 6rpx 0;
	.amount-show {
		color: $text-color;
		margin-left: 10rpx;
	}
}
.have-amount {
	position: relative;
}
.amount-trans {
	position: absolute;
	right: 0;
	top: 50%;
	height: 56rpx;
	width: 56rpx;
	margin-top: -28rpx;
	z-index: 10;
	.icon {
		width: 56rpx;
		height: 56rpx;
	}
}
.on-buystart {
	margin-top: 20rpx;
}
.sein-title {
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid $uni-text-color-grey;
}
.sein-content {
	height: calc(100vh - 998rpx);
	/* #ifdef APP-PLUS */
	height: calc(100vh - 900rpx - var(--status-bar-height));
	/* #endif */
}
.sein-nomore {
	text-align: center;
	padding-top: 80rpx;
	color: #ccc;
}
.itembox {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	font-size: $uni-font-size-sm;
  color: $color-theme;
	border-bottom: 1rpx solid $uni-text-color-grey;
	.tdtxt1 {
		width: 100rpx;
  }
	.tdtxt2 {
		width: 120rpx;
	}
	.tdtxt3 {
		width: 300rpx;
	}
	.tdain {
		color: $theme;
	}
}
</style>
